//
//  NSString+Extend.m
//  RMMaterialRed
//
//  Created by XBWH on 2024/3/7.
//

#import "NSString+Extend.h"
#define Time_Zone @"Asia/Beijing"

@implementation NSString (Extend)
-(NSString *)rb_formatNianYueRi{
    NSDate *date = [NSDate rb_dateWithDateString:self];
    return [NSString stringWithFormat:@"%ld年%02ld月%02ld日",date.year,date.month,date.day];
}
-(NSString *)rb_formatNianYue{
    NSDate *date = [NSDate rb_dateWithDateString:self];
    return [NSString stringWithFormat:@"%ld年%02ld月",date.year,date.month];
}
-(NSString *)rb_formatYueRi{
    NSDate *date = [NSDate rb_dateWithDateString:self];
    return [NSString stringWithFormat:@"%02ld月%02ld日",date.month,date.day];
}
-(NSString *)rb_formatNian{
    NSDate *date = [NSDate rb_dateWithDateString:self];
    return [NSString stringWithFormat:@"%ld年",date.year];
}
-(NSString *)rb_formatShiFenMiao{
    NSDate *date = [NSDate rb_dateWithDateString:self];
    return [NSString stringWithFormat:@"%ld时%02ld分%02ld秒",date.hour,date.minute,date.seconds];
}
-(NSString *)rb_formatShiFen{
    NSDate *date = [NSDate rb_dateWithDateString:self];
    return [NSString stringWithFormat:@"%ld时%02ld分",date.hour,date.minute];
}
-(NSString *)rb_formatFenMiao{
    NSDate *date = [NSDate rb_dateWithDateString:self];
    return [NSString stringWithFormat:@"%02ld分%02ld秒",date.minute,date.seconds];
}
-(NSString *)rb_format_yyyy_MM_dd{
   NSDate *date = [NSDate rb_dateWithDateString:self];
   return [NSString stringWithFormat:@"%ld-%02ld-%02ld",date.year,date.month,date.day];
}
-(NSString *)rb_newFormat_yyyy_MM_dd{
    NSDate *date = [NSDate rb_dateWithDateString:self];
    return [NSString stringWithFormat:@"%ld/%02ld/%02ld",date.year,date.month,date.day];
}
-(NSString *)rb_format_yyyy_MM{
    NSDate *date = [NSDate rb_dateWithDateString:self];
    return [NSString stringWithFormat:@"%ld-%02ld",date.year,date.month];
}
-(NSString *)rb_format_MM_dd{
    NSDate *date = [NSDate rb_dateWithDateString:self];
    return [NSString stringWithFormat:@"%02ld-%02ld",date.month,date.day];
}
-(NSString *)rb_newFormat_MM_dd{
    NSDate *date = [NSDate rb_dateWithDateString:self];
    return [NSString stringWithFormat:@"%02ld/%02ld",date.month,date.day];
}
-(NSString *)rb_newFormatMMdd{
    NSDate *date = [NSDate rb_dateWithDateString:self];
    return [NSString stringWithFormat:@"%02ld.%02ld",date.month,date.day];
}
-(NSString *)rb_format_yyyy{
    NSDate *date = [NSDate rb_dateWithDateString:self];
    return [NSString stringWithFormat:@"%ld",date.year];
}
-(NSString *)rb_format_HH_mm_ss{
    NSDate *date = [NSDate rb_dateWithDateString:self];
    return [NSString stringWithFormat:@"%02ld:%02ld:%02ld",date.hour,date.minute,date.seconds];
}
-(NSString *)rb_format_HH_mm{
    NSDate *date = [NSDate rb_dateWithDateString:self];
    return [NSString stringWithFormat:@"%02ld:%02ld",date.hour,date.minute];
}
-(NSString *)rb_format_mm_ss{
    NSDate *date = [NSDate rb_dateWithDateString:self];
    return [NSString stringWithFormat:@"%02ld:%02ld",date.minute,date.seconds];
}
-(NSString *)rb_formatWeekDay{
    NSString *weekStr=nil;
    NSDate *date = [NSDate rb_dateWithDateString:self];
    switch (date.weekday) {
        case 2:
            weekStr = @"星期一";
            break;
        case 3:
            weekStr = @"星期二";
            break;
        case 4:
            weekStr = @"星期三";
            break;
        case 5:
            weekStr = @"星期四";
            break;
        case 6:
            weekStr = @"星期五";
            break;
        case 7:
            weekStr = @"星期六";
            break;
        case 1:
            weekStr = @"星期天";
            break;
        default:
            break;
    }
    return weekStr;
}
///时间格式化1个小时以内：**分钟前发布
+(NSString *)rb_formatTimeDetailTimeStr:(NSString *)timeStr{
    NSString *result;
    // 将时间年月日转换成时间戳
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:Time_Zone];
    [dateFormatter setTimeZone:timeZone];
    dateFormatter.locale = [NSLocale systemLocale];
    dateFormatter.calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *date = [dateFormatter dateFromString:timeStr];
    NSTimeInterval timeInterval = [date timeIntervalSinceNow];
    timeInterval = -timeInterval;
    NSInteger timeLog = timeInterval;
    long temp = 0;
    temp = timeLog/60;
    if(temp<60){
        if(temp < 1){
            result = [NSString stringWithFormat:@"刚刚发布"];
        } else {
            result = [NSString stringWithFormat:@"%ld分钟前发布",temp];
        }
    }else{
        temp = timeLog/3600;
        if(temp>1 && temp < 12){
            result = [NSString stringWithFormat:@"%ld小时前发布",temp];
        }else{
            if(timeStr.length > 14){
                NSString *month = [[timeStr substringFromIndex:5] substringToIndex:2];
                NSString *day = [[timeStr substringFromIndex:8] substringToIndex:2];
                NSString *hour = [[timeStr substringFromIndex:11] substringToIndex:2];
                NSString *second = [[timeStr substringFromIndex:14] substringToIndex:2];
                timeStr = [NSString stringWithFormat:@"%@-%@ %@:%@",month,day,hour,second];
            }else{
                timeStr = [timeStr stringByReplacingOccurrencesOfString:@"-" withString:@"."];
            }
            result = timeStr;
        }
        if(temp == 1 || temp == 12){
            result = [NSString stringWithFormat:@"%ld小时前发布",temp];
        }
    }
    return result;
}
///时间格式化
+(NSString *)rb_timeStringYearMonthDayTimeFormat:(NSString *)timeStr{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:Time_Zone];
    [dateFormatter setTimeZone:timeZone];
    dateFormatter.locale = [NSLocale systemLocale];
    dateFormatter.calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *date = [dateFormatter dateFromString:timeStr];
    NSString *timeformat = [NSString stringWithFormat:@"%ld",(long)[date timeIntervalSince1970]];
    return timeformat;
}
//比赛时间
+(NSString *)rb_timeFormatMonthAndDay:(NSString *)timeStr{
    NSDate *now = [NSDate dateWithTimeIntervalSince1970:[[NSString rb_timeStringYearMonthDayTimeFormat:timeStr] intValue]];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
    NSString *dateString = [dateFormatter stringFromDate:now];
    NSRange range = NSMakeRange(6, 2);
    NSString *dayString = [dateString substringWithRange:range];
    NSRange monrange = NSMakeRange(4, 2);
    NSRange rangeH = NSMakeRange(8, 2);
    NSString *HString = [dateString substringWithRange:rangeH];
    NSRange rangeS = NSMakeRange(10, 2);
    NSString *SString = [dateString substringWithRange:rangeS];
    NSString *monString = [dateString substringWithRange:monrange];
    return [NSString stringWithFormat:@"%@/%@ %@:%@",monString,dayString,HString,SString];
}
///将时间年月日转换成时间戳
+(NSString *)rb_timeStringIntoYearMonDayTimeStamp:(NSString *)time{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:Time_Zone];
    [dateFormatter setTimeZone:timeZone];
    dateFormatter.locale = [NSLocale systemLocale];
    dateFormatter.calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *date = [dateFormatter dateFromString:time];
    NSString *timeStamp = [NSString stringWithFormat:@"%ld",(long)[date timeIntervalSince1970]];
    return timeStamp;
}
///将时间转换成时间戳
+(NSString *)rb_timeStringIntoTimeStamp:(NSString *)time{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    dateFormatter.locale = [NSLocale systemLocale];
    dateFormatter.calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:Time_Zone];
    [dateFormatter setTimeZone:timeZone];
    NSDate *date = [dateFormatter dateFromString:time];
    NSString *timeSp = [NSString stringWithFormat:@"%ld",(long)[date timeIntervalSince1970]];
    return timeSp;
}
///将时间戳转换成时间
+(NSString *)rb_timeStampIntoTimeString:(NSString *)time{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    dateFormatter.locale = [NSLocale systemLocale];
    dateFormatter.calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:Time_Zone];
    [dateFormatter setTimeZone:timeZone];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[time intValue]];
    NSString *dateString = [dateFormatter stringFromDate:date];
    return  dateString;
}
///获取当前时间
+(NSString *)rb_getCurrentTime{
    NSDateFormatter *formater = [[ NSDateFormatter alloc] init];
    NSDate *curDate = [NSDate date];
    [formater setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    formater.locale = [NSLocale systemLocale];
    formater.calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:Time_Zone];
    [formater setTimeZone:timeZone];
    NSString * curTime = [formater stringFromDate:curDate];
    return curTime;
}
#pragma mark - 富文本
/// 计算文字的大小,约束宽度
- (CGSize)rb_sizeWithFont:(UIFont *)font constrainedToWidth:(CGFloat)width{
    UIFont *textFont = font ? font : [UIFont systemFontOfSize:[UIFont systemFontSize]];
    CGSize textSize;
#if __IPHONE_OS_VERSION_MIN_REQUIRED < 70000
    if ([self respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {
        NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
        paragraph.lineBreakMode = NSLineBreakByWordWrapping;
        NSDictionary *attributes = @{NSFontAttributeName: textFont,
                                     NSParagraphStyleAttributeName: paragraph};
        textSize = [self boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)
                                      options:(NSStringDrawingUsesLineFragmentOrigin |
                                               NSStringDrawingTruncatesLastVisibleLine)
                                   attributes:attributes
                                      context:nil].size;
    } else {
        textSize = [self sizeWithFont:textFont
                    constrainedToSize:CGSizeMake(width, CGFLOAT_MAX)
                        lineBreakMode:NSLineBreakByWordWrapping];
    }
#else
    NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
    paragraph.lineBreakMode = NSLineBreakByWordWrapping;
    NSDictionary *attributes = @{NSFontAttributeName: textFont,
                                 NSParagraphStyleAttributeName: paragraph};
    textSize = [self boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)
                                  options:(NSStringDrawingUsesLineFragmentOrigin |
                                           NSStringDrawingTruncatesLastVisibleLine)
                               attributes:attributes
                                  context:nil].size;
#endif
    return CGSizeMake(ceil(textSize.width), ceil(textSize.height));
}
/// 计算文字的大小,约束高度
- (CGSize)rb_sizeWithFont:(UIFont *)font constrainedToHeight:(CGFloat)height{
    UIFont *textFont = font ? font : [UIFont systemFontOfSize:[UIFont systemFontSize]];
    CGSize textSize;
#if __IPHONE_OS_VERSION_MIN_REQUIRED < 70000
    if ([self respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {
        NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
        paragraph.lineBreakMode = NSLineBreakByWordWrapping;
        NSDictionary *attributes = @{NSFontAttributeName: textFont,
                                     NSParagraphStyleAttributeName: paragraph};
        textSize = [self boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, height)
                                      options:(NSStringDrawingUsesLineFragmentOrigin |
                                               NSStringDrawingTruncatesLastVisibleLine)
                                   attributes:attributes
                                      context:nil].size;
    } else {
        textSize = [self sizeWithFont:textFont
                    constrainedToSize:CGSizeMake(CGFLOAT_MAX, height)
                        lineBreakMode:NSLineBreakByWordWrapping];
    }
#else
    NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
    paragraph.lineBreakMode = NSLineBreakByWordWrapping;
    NSDictionary *attributes = @{NSFontAttributeName: textFont,
                                 NSParagraphStyleAttributeName: paragraph};
    textSize = [self boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, height)
                                  options:(NSStringDrawingUsesLineFragmentOrigin |
                                           NSStringDrawingTruncatesLastVisibleLine)
                               attributes:attributes
                                  context:nil].size;
#endif
    return CGSizeMake(ceil(textSize.width), ceil(textSize.height));
}
///获取文字高度
+(CGFloat)rb_height:(NSString*)text width:(CGFloat)width space:(CGFloat)space font:(UIFont*)font {
    if (text.length == 0) {
        return 0;
    }
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:space];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, text.length)];
    [attributedString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, text.length)];
    CGFloat attributeH = [attributedString boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin context:nil].size.height;
    return attributeH;
}
///获取文字行数
+ (NSInteger)rb_lineNum:(NSString*)text width:(CGFloat)width space:(CGFloat)space font:(UIFont*)font{
    CGFloat textH = [NSString rb_height:text width:width space:space font:font];
    CGFloat lineHeight = font.lineHeight;
    return textH / lineHeight;
}
///传给后台拼接后的字符
+(NSString *)rb_spliceStringWithArray:(NSMutableArray *)array{
    //上传的值(如:@"1,2,3")
    //给后台传一个拼接后的字符串
    NSString *spliceString = @"";
    for (int i = 0; i < array.count; i++) {
        NSString *strAll = [NSString stringWithFormat:@"%@",array[i]];
        if (array.count == 1) {
            spliceString = strAll;
        }else if(array.count != 0){
            if (i != array.count-1) {
                strAll = [NSString stringWithFormat:@"%@%@",strAll,@","];
            }
            spliceString = [spliceString stringByAppendingString:[NSString stringWithFormat:@"%@",strAll]];
        }
    }
    return spliceString;
}
///将字典或数组转换成字符串
+(NSString *)rb_objectToJson:(id)obj{
    if (obj == nil) {
        return @"";
    }
    NSError *error = nil;
    NSData *jsonData = [NSString rb_dataWithJSONObject:obj options:0 error:&error];

    if ([jsonData length] && error == nil) {
        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    } else {
        return @"";
    }
}
+(NSData *)rb_dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error {
    if (obj) {
        return [NSJSONSerialization dataWithJSONObject:obj options:opt error:error];
    } else {
        return [NSData new];
        ;
    }
}
/// 若字符串为<null>，则返回一个空字符串，反正返回自身
-(NSString *)rb_editNullStr{
    if ([self isEqual:[NSNull null]]|| self == nil || [self isEqualToString:@"<null>"] || self.length==0) {
        return @"";
    }
    
    return self;
}
///添加图片
+(NSMutableAttributedString *)rb_insterImageWithAttributedString:(NSString *)content WithImageName:(NSString *)imageName WithCGRectMake:(CGRect)bounds WithIsInterTail:(BOOL)isIsInterTail{
    //拿到整体的字符串
    NSString *textStr = [NSString stringWithFormat:@" %@ ",content];
    NSMutableAttributedString * attriStr = [[NSMutableAttributedString alloc] initWithString:textStr];
    NSTextAttachment *attchImage = [[NSTextAttachment alloc] init];
    // 表情图片
    attchImage.image = [UIImage imageNamed:imageName];
    if (isIsInterTail) {//插入到尾部
        textStr = content;
    }
    attchImage.bounds = bounds;
    NSAttributedString *stringImage = [NSAttributedString attributedStringWithAttachment:attchImage];
    //将图片插入到合适的位置
    if(isIsInterTail){//插入到尾部
        [attriStr appendAttributedString:stringImage];
    }else{
        [attriStr insertAttributedString:stringImage atIndex:0];
    }
    return attriStr;
}
///添加多张图片
+(NSMutableAttributedString *)rb_insterImageWithAttributedString:(NSString *)content WithImageNames:(NSArray *)imageNames WithImageBounds:(NSArray *)imageBounds{
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@""];
    for (int index = 0; index<imageNames.count; index++) {
        NSString *imageName = imageNames[index];
        CGRect bounds = [imageBounds[index] CGRectValue];
        NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
        textAttachment.image = [UIImage imageNamed:imageName];
        textAttachment.bounds = bounds;
        NSAttributedString *attrStringWithImage = [NSAttributedString attributedStringWithAttachment:textAttachment];
        // 添加一个空格字符作为图片与文本之间的间距
        NSAttributedString *spaceString = [[NSAttributedString alloc] initWithString:@" "];
        [attributedString appendAttributedString:spaceString];
        [attributedString appendAttributedString:attrStringWithImage];
    }
    //拿到整体的字符串
    NSString *textStr = [NSString stringWithFormat:@"  %@",content];
    NSAttributedString *textString = [[NSAttributedString alloc] initWithString:textStr];
    [attributedString appendAttributedString:textString];
    return attributedString;
}
#pragma mark - js标签
///清除html标签
-(NSString *)rb_stringByStrippingHTML{
    return [self stringByReplacingOccurrencesOfString:@"<[^>]*>|\r\n" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, self.length)];
}
///清除js脚本
-(NSString *)rb_stringByRemovingScriptsAndStrippingHTML{
    NSMutableString *mString = [self mutableCopy];
    NSError *error;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<script[^>]*>[\\w\\W]*</script>" options:NSRegularExpressionCaseInsensitive error:&error];
    NSArray *matches = [regex matchesInString:mString options:NSMatchingReportProgress range:NSMakeRange(0, [mString length])];
    for (NSTextCheckingResult *match in [matches reverseObjectEnumerator]) {
        [mString replaceCharactersInRange:match.range withString:@""];
    }
    return [mString rb_stringByStrippingHTML];
}
///截取两个字符串中间的内容
-(NSString *)rb_stringSubstringWithStringStart:(NSString *)subStringStart WithStringEnd:(NSString *)subStringEnd{
    NSRange rangeStart = [self rangeOfString:subStringStart];
    NSRange rangeEnd = [self rangeOfString:subStringEnd];
    if (rangeStart.location != NSNotFound && rangeEnd.location != NSNotFound && rangeEnd.location > rangeStart.location) {
        NSRange subStringRange = NSMakeRange(rangeStart.location + rangeStart.length, rangeEnd.location - rangeStart.location - rangeStart.length);
        NSString *extractedString = [self substringWithRange:subStringRange];
        return extractedString;
    }else{
        return @"";
    }
}
///将NSString类型转化为NSdate类型
+(NSDate*)rb_NSStringChangeDateFormat:(NSString*)dateFormat datestring:(NSString*)datestring{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:dateFormat];
    NSDate *date = [dateFormatter dateFromString:datestring];
    return date;
}
///根据数字返回周几
+(NSString *)rb_NSStringReplaceWeekDay:(NSString *)num{
    if ([num isEqualToString:@"7"]) {
        return  @"周日";
    }else if ([num isEqualToString:@"6"]){
        return  @"周六";
    }else if ([num isEqualToString:@"5"]){
        return  @"周五";
    }else if ([num isEqualToString:@"4"]){
        return  @"周四";
    }else if ([num isEqualToString:@"3"]){
        return  @"周三";
    }else if ([num isEqualToString:@"2"]){
        return  @"周二";
    }else if ([num isEqualToString:@"1"]){
        return  @"周一";
    }else{
        return @"";
    }
}
@end
